mui.plusReady(function() {

	var state = app.getState();
	var uid = state.user_id;
	var ws;
	var loginFlag = false;
	var hasFresh = false;
	// 在程序运行时接收到的消息显示在系统消息中心 
	//plus.push.setAutoNotification(true); 
	//保持唤醒状态
	//plus.device.setWakelock(true);
	/*
	function wainshow() {
		if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
			loginFlag = false;
			mui.toast("网络异常，请检查网络设置！");
		} else {}
	}
	document.addEventListener("netchange", wainshow, false);*/
	window.addEventListener('show', function() {
		//console.log(state.user_id);
		//var state = app.getState();
	}, false);
	/*
	function createLocalPushMsg(title, str) {
		plus.push.clear();
		var options = {
			cover: true,
			title : title,
			sound : "none"
		};
		//var str = dateToStr(new Date());
		//str = "欢迎使用Html5 Plus创建本地消息！";
		plus.push.createMessage(str, "LocalMSG", options);
		
		outSet("创建本地消息成功！");
		outLine("请到系统消息中心查看！");
		if(plus.os.name == "iOS") {
			outLine('*如果无法创建消息，请到"设置"->"通知"中配置应用在通知中心显示!');
		}
	}

	function getPushInfo() {
		var info = plus.push.getClientInfo();
		//outSet("获取客户端推送标识信息：");
		console.log("token: " + info.token);
		console.log("clientid: " + info.clientid);
		console.log("appid: " + info.appid);
		console.log("appkey: " + info.appkey);
	}

	function listAllPush() {
		var msgs = null;
		switch(plus.os.name) {
			case "Android":
				msgs = plus.push.getAllMessage();
				break;
			default:
				break;
		}
		if(!msgs) {
			outSet("此平台不支持枚举推送消息列表！");
			return;
		}
		outSet("枚举消息列表（" + msgs.length + "）：");
		for(var i in msgs) {
			var msg = msgs[i];
			outLine(i + ": " + msg.title + " - " + msg.content);
		}
	}
	
	function pushGetRun(payload) {
		payload = JSON.parse(payload);
		var id = payload.id;
		var autoShow = payload.autoshow;
		var event = payload.event;
		var params = JSON.stringify(payload.params);
		//...... //用参数打开指定页面
	}
	//获取通知栏（app未启动）点击、第三方程序启动本app
	function openWebviewFromOthers() {
		var args = plus.runtime.arguments;
		if(args) {
			pushGetRun(args);
		}
	}
	//getPushInfo();
	plus.push.addEventListener("click", function(msg) {
		console.log("push click");
		pushGetRun(msg.payload);
	}, false);
	*/
	/*
	plus.push.addEventListener("receive", function(msg) {
		//获取透传数据
		var data = JSON.parse(msg.payload);
		//创建本地消息
		plus.push.createMessage(data.content, data.payload, {
			title: data.title,
			cover: false
		});
	}, false);*/
	window.addEventListener('addFriends', function(event) {
		var rtinfo = event.detail;
		pollingSend(rtinfo);
		//document.getElementById('hasmsg').style.display = '';

	});
	window.addEventListener('hasHongbao', function(event) {
		var rtinfo = event.detail;
		setTimeout(function(){pollingSend(rtinfo);},1000);
		
		//document.getElementById('hasmsg').style.display = '';

	});
	window.addEventListener('passFriends', function(event) {
		document.getElementById('hasmsg').style.display = 'none';
		//document.getElementById('hasmsg1').style.display = 'none';
		var rtinfo = event.detail;
		var msgInfo = {
			type: 'say',
			id: chat.getId(rtinfo.f_id),
			user_id: rtinfo.user_id,
			user_name: state.name,
			user_header: state.avatar ? state.avatar : '',
			room_id: rtinfo.f_id,
			chat_name: rtinfo.f_name,
			header: rtinfo.f_avatar,
			msg: '你们成为了好友',
			ftype: 'tip', //聊天类型
			ctype: 1, //聊天室类型
			extras: '{}'
		};
//		console.log(JSON.stringify(msgInfo));
		pollingSend(msgInfo);
		var info = {
			id: msgInfo.id,
			f_id: msgInfo.user_id,
			f_name: msgInfo.user_name,
			f_header: msgInfo.user_header,
			t_header: msgInfo.header,
			t_name: msgInfo.chat_name,
			t_msg: msgInfo.msg,
			t_id: msgInfo.room_id,
			ctype: 1,
			r_type: 'tip',
			extras: JSON.stringify(msgInfo.extras),
			isread: 0,
			m_id: 0,
			add_time: Date.parse(new Date()) / 1000
		};
//		console.log(JSON.stringify(msgInfo));
		//更新列表
		chat.set(msgInfo.room_id, info);
		

	});
	window.addEventListener('sendMsg', function(event) {
		var rtinfo = event.detail;
		//ws.send(JSON.stringify(rtinfo));
		//console.log(JSON.stringify(rtinfo));  
		pollingSend(rtinfo);
		var chatWin = plus.webview.getWebviewById('chat.html');
		mui.fire(chatWin, 'refreshList', null);

	});

	function loginChat() {
		state.type = 'loginchatindex';
		pollingSend(state);
	}

	window.addEventListener('login', function(event) {
		loginChat();
		loginFlag = true;
	});
	window.addEventListener('addvideo', function(event) {
		var room_id = event.detail.room_id;
		state.type = 'addvideo';
		state.room_id = room_id;
		pollingSend(JSON.stringify(state));
	});
	window.addEventListener('loginroom', function(event) {
		var rtinfo = event.detail;
		pollingSend(rtinfo);
	});
	window.addEventListener('joinroom', function(event) {
		var rtinfo = event.detail;
		rtinfo.type = 'joinroom';
		pollingSend(rtinfo);
	});
	window.addEventListener('cutvideoMe', function(event) {
		var rtinfo = event.detail;
		pollingSend(rtinfo);
	});
	window.addEventListener('cutvideoTo', function(event) {
		var rtinfo = event.detail;
		pollingSend(rtinfo);
	});
	window.addEventListener('changeSound', function(event) {
		var rtinfo = event.detail;
		pollingSend(rtinfo);
	});
	window.addEventListener('changeVideo', function(event) {
		var rtinfo = event.detail;
		pollingSend(rtinfo);
	});

	function playSound(name,rtinfo) {
		// 需要每次都重新读取设置，否则设置页面修改后无法同步
		var set = app.getSettings();
			
		if(!set['voicemsg'] || set['voicemsg'] === 0) {
			
			var player = document.createElement('audio');
			player.src = 'static/sound/' + name + '.mp3';
			player.volume = 1;
			player.loop = false;
			player.play();
			if(rtinfo) {
				//createLocalPushMsg(rtinfo['f_name'],app.parseMainMsg(rtinfo['t_msg'], rtinfo['r_type']));
			}
			
		}
		if(!set['vibratemsg'] || set['vibratemsg'] === 0) {
			plus.device.vibrate(800);
		}
		///plus.device.beep(3); 
	}

	function mymessage(data) {
		var rtinfo = data.rtinfo;
		var chatWin = plus.webview.getWebviewById('chat.html');
		//var roomWin = plus.webview.getWebviewById('room.html');
		var boxWin = plus.webview.getWebviewById('chatbox');
		var activeTab = localStorage.getItem('defaultTab');
		//console.log(data['type']);
//		console.log(JSON.stringify(rtinfo));
		switch(data['type']) {
			// 服务端ping客户端
			case 'ping':
				break;
				// 登录 更新用户列表
			case 'loginchatindex':
				if(data.update && data.update > 0) {
					//app.updateSoft();
				}
				//chat.updateList();
				mui.fire(chatWin, 'refreshList', null);

				//if(activeTab == 'chat.html') {
				//mui.fire(chatWin, 'refreshList', null);
				//mui.fire(plus.webview.getWebviewById('chatbox'),'refreshSay', rtinfo);
				//}
				//renderlist(); 
				break;
				// 发言
			case 'sayme':
				console.log('来消息了！');

				//if(activeTab == 'chat.html') {
				if(uid !== rtinfo['f_id']) {
					//hasFresh = true;
					playSound('tip',rtinfo);
					chat.set(rtinfo['f_id'], rtinfo);

				} else {
					console.log('自己来消息了！');
				}

				// modify by yaozy 修改为在打开聊天窗口的时候不刷新列表以提升性能
				if (boxWin) {
					mui.fire(boxWin, 'refreshSay', rtinfo);
				} else {
					mui.fire(chatWin, 'refreshList', null);
				}
				
//				mui.fire(chatWin, 'refreshList', null);
//				mui.fire(boxWin, 'refreshSay', rtinfo);

				//}
				//renderlist();
				break;
			case 'sayroom':
				console.log('来群消息了！');

				//if(activeTab == 'room.html') {
				if(uid !== rtinfo['f_id']) {
					playSound('tip',rtinfo);
					chat.set(rtinfo['t_id'], rtinfo);
				} else {
					console.log('自己来群消息了！');
				}
				
				// modify by yaozy 修改为在打开聊天窗口的时候不刷新列表以提升性能
				if (boxWin) {
					mui.fire(boxWin, 'refreshSay', rtinfo);
				} else {
					mui.fire(chatWin, 'refreshList', null);
				}
				
//				mui.fire(chatWin, 'refreshList', null);
//				mui.fire(boxWin, 'refreshSay', rtinfo);
				//}
				//renderlist();
				break;
				//case saylist
				// 用户退出 更新用户列表
			case 'comvideo':
				if(data['online'] > 0) {
					var videoWin = '/pages/chat/video_chat.html';
					mui.openWindow({
						id: videoWin,
						url: videoWin,
						extras: JSON.stringify(rtinfo)
					});
				} else {
					mui.alert("对方不在线！");
					var service_comfirm = plus.webview.getWebviewById("video_wait.html");
					service_comfirm && plus.webview.close(service_comfirm, "none");
					plus.nativeUI.closeWaiting();
				}
				break;
			case 'cutvideoMe':
				var service_comfirm = plus.webview.getWebviewById("/pages/chat/video_chat.html");
				service_comfirm && plus.webview.close(service_comfirm, "none");
				mui.alert("发起方挂断了！");
				break;
			case 'cutvideoTo':
				var service_comfirms = plus.webview.getWebviewById("video_wait.html");
				service_comfirms && plus.webview.close(service_comfirms, "none");
				mui.alert("接收方挂断了！");
				break;
			case 'changeSound':
				mui.alert("对方切换到声音！");
				break;
				//调起声音流
			case 'changeVideo':
				mui.alert("对方切换到视频！");
				//调起视频流
				break;
			case 'addfriends':
				document.getElementById("hasmsg").style.display = '';
				playSound('di');
				//document.getElementById("hasmsg1").style.display = '';
				//var findwin = plus.webview.getWebviewById("contact.html");
				mui.fire(chatWin, 'hasFriends', null);
				
				//mui.alert("对方切换到声音！");
				break;
			case 'hasHongbao':
				playSound('di');
				var btnArray = ['确定', '取消'];
				//var msg = "您的红包被" + rtinfo['username'] + "领取了" + rtinfo['money'] + rtinfo['coinname'] + "请确认发送！";
				var msg = "您的红包被人领取了，请确认发送！";
				mui.confirm(msg, '红包消息', btnArray, function(e) {
					if (e.index == 0) {
						mui.openWindow({
							url : 'pages/coin/mypacket.html',
							id : 'mypacket',
							createNew : true
						});
					} else {
						mui.toast('取消后您可以到钱包管理-》群红包查看确认');
					}
				})
				//mui.alert();
				break;
			default:
				console.log('no type' + data['type']);
				break;
		}
	}
/*
	function pollingSend(data) {
		//console.log('1');
		//console.log(JSON.stringify(data));
		//var data = JSON.parse(data);
		//data.ptype = 'send';
		if(data.extras) {
			data.extras = JSON.stringify(data.extras);
		}
		
		var s = apiurl + 'api/send?';
		for(var p in data) {
			s += p + '=' + data[p] + '&';
		}
		console.log(s);
		mui.ajax({
			url: apiurl + 'api/send',
			data: data,
			async: true,
			dataType: 'json',
			crossDomain: true, //强制使用5+跨域
			type: 'post',
			timeout: 10000,
			success: function(res) {
				//console.log('polling send success!');
			},
			error: function(xhr, type, errorThrown) {
				//console.log(JSON.stringify(xhr));
				console.log('send' + JSON.stringify(type));
				//console.log(JSON.stringify(errorThrown));
				mui.toast('请检查你的联网状态！');
			}
		});
	}*/
	/*setInterval(function() {
		//console.log(apiurl + 'api/msg?user_id=' + uid);
		mui.getJSON(apiurl + 'api/msg?user_id=' + uid, function(res) {
			//console.log(JSON.stringify(res));
			if(res && res.status && res.status > 0) {
				
				mymessage(res);
			}
		});
	}, 1000);*/
	/*
	function pollingMessage() {
		//state.ptype = message;
		//console.log(apiurl + 'api/msg');

		mui.ajax({
			url: apiurl + 'api/msg',
			data: state,
			async: true,
			dataType: 'json',
			crossDomain: true, //强制使用5+跨域
			type: 'get',
			timeout: 10000,
			success: function(res) {
				//console.log('pollingSend success!');
				//console.log(JSON.stringify(res)); 
				if(res && res.status && res.status > 0) {
					mymessage(res);
				}
				setTimeout(function() {
					pollingMessage();
				}, 1200);
				//mymessage(data);
				//pollingMessage();

			},
			error: function(xhr, type, errorThrown) {
				//console.log(JSON.stringify(xhr));
				//console.log('msg' + JSON.stringify(type));
				//console.log(JSON.stringify(errorThrown));
				//mui.toast('请检查你的联网状态！');
				setTimeout(function() {
					pollingMessage();
				}, 1000);
			}
		});
	}
	pollingMessage();
	*/
	
	//console.log(JSON.stringify(window.MozWebSocket));
	
	var pollingSend = function(data) {
		ws.send(JSON.stringify(data));
	}

	function usepolling() {
		//ws = {};
		//ws.send = pollingSend;
		// pollingSend = pollingSendajax;
		// pollingMessage();
	}
	runnum = 0;
	
	connect = function() {

		// 创建websocket
		ws = new WebSocket(chaturl);
		// 当socket连接打开时，输入用户名
		ws.onopen = onopen;
		// 当有消息时根据消息类型显示不同信息
		ws.onmessage = onmessage;
		ws.onclose = function(e) {
			console.log("连接关闭，定时重连");
			setTimeout(function() {
				//loginFlag = false;
				runnum++;
				console.log(runnum);
				if(runnum < 5) {
					connect();
					//plus.nativeUI.toast("请检查你的联网状态！");
				} else {
					return;
					//usepolling();
					//connect();
				}

			}, 300);

		};
		ws.onerror = function(e) {
			console.log("出现错误");
			//console.log(JSON.stringify(e));
		};
	}
	//var currentWin = plus.webview.getWebviewById("activeTab");
	// 连接建立时发送登录信息
	function onopen() {
		console.log("websocket握手成功!");
		loginChat();
	}

	// 服务端发来消息时
	function onmessage(e) {
		var data = eval("(" + e.data + ")");
		mymessage(data);
	}
	connect();
});